from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..crud.paper_crud import get_paper_by_grade_subject
from ..crud.textbook_crud import get_textbook_by_grade_subject, get_textbook_by_id
from ..database.db import get_db
from ..crud.subject_crud import get_all_subjects
from ..crud.grade_crud import get_all_grades
from ..crud.sources_crud import get_all_sources
from ..schemas.base import ResponseModel
from pydantic import BaseModel,Field
from typing import List

category=APIRouter(prefix="/category", tags=["分类"])
class SubjectItem(BaseModel):
    id: int
    name: str

class GradeItem(BaseModel):
    id: int
    name: str

class SourceItem(BaseModel):
    id: int
    name: str

class CategoryData(BaseModel):
    subjects: List[SubjectItem]
    grades: List[GradeItem]
    sources: List[SourceItem]

class CategoryResponse(ResponseModel):
    data: CategoryData
@category.get("/")
async def get_category():
    return {"message":"hello category"}

@category.get("/tree",response_model=CategoryResponse)
async def get_category_tree(db: Session = Depends(get_db)):
    subjects = get_all_subjects(db)
    grades = get_all_grades(db)
    sources = get_all_sources(db)
    data={
        "subjects":subjects,
        "grades":grades,
        "sources":sources
    }
    return CategoryResponse(code=200,message="success",data=data)
class QueryRequest(BaseModel):
    subject: str =Field(default="语文")
    grade: str = Field(default="七年级")
    source: str = Field(default="textbook")
    page:int=Field(default=1,ge=1)
    page_size:int=Field(default=10,ge=1)

class QueryResponseDataDetail(BaseModel):
    subject: SubjectItem
    grade: GradeItem
    source: SourceItem
    items: List[dict]  # 实际数据项，格式根据表不同而变化

class QueryResponse(ResponseModel):
    data: QueryResponseDataDetail

def get_model_class(source: str):
    from ..models.textbook_model import Textbook
    from ..models.paper_model import Paper
    from ..models.videos_model import Videos

    if source == "textbook":
        return Textbook
    elif source == "paper":
        return Paper
    elif source == "video":
        return Videos
@category.post("/query")
async def query_category(
    params: QueryRequest,
    db: Session = Depends(get_db)
):
    flag=""
    a=[]
    global total_page
    if params.source=="textbook":
        textbooks,total_page = get_textbook_by_grade_subject(db, params.grade, params.subject,params.page,params.page_size)
        print(textbooks)
        flag="textbook"
        a.append(textbooks)
    elif params.source=="paper":
        papers ,total_page= get_paper_by_grade_subject(db, params.grade, params.subject,page=params.page,page_size=params.page_size)
        flag="paper"
        a.append(papers)
    return ResponseModel(code=200, message="success", data=a, total_page=total_page)


